package com.szosen.json.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.szosen.json.database.DaoMaster.DevOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class JSONDBService {
	private static DevOpenHelper mHelper;
	private static SQLiteDatabase mDatabase;
	private static DaoMaster mDaoMaster;
	private static DaoSession mDaoSession;
	private static JSONDBService sAppDB = null;

	// ****************************数据操作*************************************************
	private static ArchiveBeanDao mArchiveBeanDao;

	private JSONDBService(Context context) {
		mHelper = new DaoMaster.DevOpenHelper(context, "health2.db", null);
		mDatabase = mHelper.getWritableDatabase();
		mDaoMaster = new DaoMaster(mDatabase);
		mDaoSession = mDaoMaster.newSession();
		mArchiveBeanDao = mDaoSession.getArchiveBeanDao();
	}

	public static synchronized JSONDBService getInstance(Context context) {
		if (sAppDB == null) {
			sAppDB = new JSONDBService(context);
		}
		return sAppDB;
	}

	public static boolean add(Object object) {
		boolean tag = true;
		long temp = -1;
		if (object instanceof ArchiveBean) {
			temp = mArchiveBeanDao.insertOrReplace((ArchiveBean) object);
		} else {
			tag = false;
		}
		if (temp < 0) {
			tag = false;
		}
		return tag;
	}

	public static void update(Object object) {
		boolean tag = true;
		if (object instanceof ArchiveBean) {
			mArchiveBeanDao.update((ArchiveBean) object);
		}
	}

	/** 通过对象获取所有的集合数据。 */
	public static List<Object> getAll(Object object) {
		if (object instanceof ArchiveBean) {
			return new ArrayList<Object>(mArchiveBeanDao.loadAll());
		}
		return null;
	}

	/***
	 * 通过唯一性来查询数据的。
	 *
	 * @param object
	 * @return
	 */
	public static Object queryByKey(Object object) {
		if (object instanceof ArchiveBean) {
			return mArchiveBeanDao
					.queryBuilder()
					.where(ArchiveBeanDao.Properties.Time
							.eq(((ArchiveBean) object).getTime() + "")).list();
		}
		return object;
	}

	/***
	 * 通过idcard来查询集合数据。
	 *
	 * @param object
	 * @return
	 */
	public static Object queryByIdCard(Object object) {
		if (object instanceof ArchiveBean) {
			return mArchiveBeanDao
					.queryBuilder()
					.where(ArchiveBeanDao.Properties.Idcard
							.eq(((ArchiveBean) object).getIdcard() + ""))
					.list();
		}
		return object;
	}

	/***
	 * 删除单条记录
	 *
	 * @param object
	 */
	public static void delete(Object object) {
		if (object instanceof ArchiveBean) {
			mArchiveBeanDao.delete((ArchiveBean) object);
		}
	}

	/** 删除该对象对应的所有数据。 */
	public static void deleteAll(Object object) {
		if (object instanceof ArchiveBean) {
			mArchiveBeanDao.deleteAll();
		}
	}

}
